<template>
  <div class="msg-item" :class="{'right': msg.content.from_id === IMUser.username}">
    <!-- 头像 -->
    <img :src="chatUserInfo.avatar" alt="" width="48" height="48" class="avatar" v-if="chatUserInfo.avatar">
    <img src="./person_01.png" alt="" width="48" height="48" class="avatar" v-else>
    <div class="content">
      <div v-if="msg.content.target_type === 'group'" class="name">{{msg.content.from_name||chatUserInfo.nickname}}</div>
      <!-- 内容 -->
      <div v-if="msg.content.msg_type === 'text'" class="text" v-html="msg.content.msg_body.text"></div>
      <div v-if="msg.content.msg_type === 'image'">
        <img :src="picture" alt="" class="picture">
      </div>
      <div v-if="msg.content.msg_type === 'file'"></div>
    </div>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
export default {
  name: 'messageItem',
  props: {
    msg: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      picture: '',
      chatUserInfo: {}
    }
  },
  computed: {
    ...mapGetters({
      IMUser: 'loginUser',
    }),    
  },
  methods: {
    getPicture(){
      this.$store.dispatch('getMedia', this.msg.content.msg_body.media_id).then(res =>{
        this.picture = res.url;
        setTimeout(() => {
          this.$emit('loaded');
        }, 300);
      })
    },
    getUserAvatar(){
      this.$store.dispatch('getChatUserInfo', this.msg.content.from_id).then(res =>{
        this.chatUserInfo = res.user_info;
      })
    }
  },
  mounted() {
    this.getUserAvatar();
    if (this.msg.content.msg_type === 'image') {
      this.getPicture();
    }
  },
  watch: {
    "msg.msg_id": function(val, oldVal){
      this.getUserAvatar();
      if ('image' === this.msg.content.msg_type) {
        this.getPicture();        
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.picture{
  max-width: 50%;
}
.right{
  text-align: right;
  flex-direction: row-reverse !important;
  .tiem{
    .text{
      background: rgb(197, 199, 199) !important;
      color: black !important;
    }
  }
}
.msg-item{
  width: 100%;
  margin-top: 16px;
  display: flex;
  flex-direction: row;
  align-items: stretch;
  .avatar{
    border-radius: 4px;
  }
  .content{
    margin: auto 8px;
    padding: 0;
    background: no-repeat;
    .name{
      margin-bottom: 8px;
    }
    .text{
      display: inline-block;
      font-size: 16px;
      line-height: 24px;
      padding: 0px 5px;
      border-radius: 3px;  
      background: rgba(24, 206, 180, 1);
      color: white;    
      text-align: left;
      white-space: pre-wrap;
    }
    .picture{
      border-radius: 3px;
    }
  }
}
</style>